﻿namespace JanusLibAing.AutoSave
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Simple implementation of Abstract factory
    /// I want want simple way to add a new classes
    /// </summary>
    public abstract class XmlStorageFactory
    {
        private Dictionary<string, Type> dataItemFabric = new Dictionary<string, Type>();

        /// <summary>
        /// Creates the data item.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public IDataItem CreateDataItem(string key, string value)
        {
            if (!dataItemFabric.ContainsKey(key))
            {
                RegisterAllDataItem();
            }

            if (dataItemFabric.ContainsKey(key))
            {
                Type dataItemType = dataItemFabric[key];
                IDataItem instance = (IDataItem)Activator.CreateInstance(dataItemType);
                instance.ParseValue(value);
                return instance;
            }

            // here it is possible to throw exception but we don't need it now
            return null;
        }

        /// <summary>
        /// Registers the data item for reading
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="dataItemType">Name of the class.</param>
        public void RegisterDataItem(string key, Type dataItemType)
        {
            if (!dataItemFabric.ContainsKey(key))
            {
                dataItemFabric.Add(key, dataItemType);
            }
        }

        /// <summary>
        /// Registers all data item.
        /// </summary>
        public abstract void RegisterAllDataItem();

    }
}